#用于访问btctrade现货的rest api
from lib.utilBtctrade import request, sort_and_format, getDepth
from lib.settings import BTCTRADE_API_URL
import config

class Btctrade(object):
    def __init__(self):  # url使用BTCTRADE_API_URL['host']
        self.__url = BTCTRADE_API_URL['host']
        self.__apikey = config.BTCTRADE_API_KEY
        self.__secretkey = config.BTCTRADE_SECRET_TOKEN
        self.fee = BTCTRADE_API_URL['fee']

        self.btc_free = 0.0  # 账户情况
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0

        self.bid = 0.0  # 买一卖一情况
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0


    '''
    获取btctrade市场深度信息
    '''
    def update_depth(self):
        try:
            response = getDepth()
            if not response:
                self.bid = 0.0
                self.bid_volume = 0.0
                self.ask = 0.0
                self.ask_volume = 0.0
                return False
            if response and response['result']==True:
                self.bid = float(sort_and_format(response['bids'], True)[0]['price'])
                self.bid_volume = float(sort_and_format(response['bids'], True)[0]['volume'])
                self.ask = float(sort_and_format(response['asks'], False)[0]['price'])
                self.ask_volume = float(sort_and_format(response['asks'], False)[0]['volume'])
                return True
            else:
                self.bid = 0.0
                self.bid_volume = 0.0
                self.ask = 0.0
                self.ask_volume = 0.0
                return False
        except Exception as e:
            print(e)
            self.bid = 0.0
            self.bid_volume = 0.0
            self.ask = 0.0
            self.ask_volume = 0.0
            return False


    '''
    更新用户现货账户信息
    '''
    def update_accountInfo(self):
        try:
            params = {}
            response = request(BTCTRADE_API_URL['account_info'], params, self.__apikey, self.__secretkey)
            if not response:
                self.btc_free = 0
                self.btc_frozen = 0
                self.cny_free = 0
                self.cny_frozen = 0
                return False
            if response and 'message' in response:
                self.btc_free = 0
                self.btc_frozen = 0
                self.cny_free = 0
                self.cny_frozen = 0
                return False
            self.btc_free = float(response['btc_balance'])
            self.btc_frozen = float(response['btc_reserved'])
            self.cny_free = float(response['cny_balance'])
            self.cny_frozen = float(response['cny_reserved'])
            return True

        except Exception as e:
            print(e)
            self.btc_free = 0
            self.btc_frozen = 0
            self.cny_free = 0
            self.cny_frozen = 0
            return False


    '''
    买入比特币
    '''
    def buy(self, price, amount):
        try:
            params = {}
            params['coin'] = 'btc'
            params['price'] = price
            params['amount'] = amount
            response = request(BTCTRADE_API_URL['buy'], params, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response and response['result']==False:
                return False
            return str(response['id'])
        except Exception as e:
            print(e)
            return False


    '''
    卖出比特币
    '''
    def sell(self, price, amount):
        try:
            params = {}
            params['coin'] = 'btc'
            params['price'] = price
            params['amount'] = amount
            response = request(BTCTRADE_API_URL['sell'], params, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response and response['result']==False:
                return False
            return str(response['id'])
        except Exception as e:
            print(e)
            return False


    '''
    现货订单信息查询
    #返回结果示例：
    #{"id":123,"datetime":"2013-01-02 14:09:01","type":"buy","price":543, "amount_original":1.234,"amount_outstanding":1.234,"status":"open"}
    '''
    def order_info(self, orderId):
        try:
            if orderId == False:
                return False
            params = {}
            params['id'] = orderId
            response = request(BTCTRADE_API_URL['order_info'], params, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response and 'message' in response:
                return False
            if response['status'] == 'open':
                return 'cancelable'
            else:
                return 'ircancelable'
        except Exception as e:
            print(e)
            return False


    '''
    查询现货未成交订单
    '''
    def get_orders(self):
        try:
            params = {}
            params['coin'] = 'btc'
            response = request(BTCTRADE_API_URL['get_orders'], params, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response and 'message' in response:
                return False
            return response
        except Exception as e:
            print(e)
            return False


    '''
    取消订单
    '''
    def cancel_order(self, orderId):
        try:
            if not orderId:
                return False
            params = {}
            params['id'] = orderId
            response = request(BTCTRADE_API_URL['cancel_order'], params, self.__apikey, self.__secretkey)
            if not response:
                return False
            if response and response['result'] == False:
                return False
            return True
        except Exception as e:
            print(e)
            return False


    '''
    取消所有未成交订单
    '''
    def cancel_all(self):
        response = self.get_orders()
        if not response:
            return False
        for order in response:
            self.cancel_order(order['id'])

